package com.xx.eshop.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xx.eshop.entity.AttrValue;
import com.xx.eshop.service.AttrService;
import com.xx.eshop.service.AttrValueService;

@Controller
public class ValueController {
	
	@Autowired
	private AttrService attrService;
	@Autowired
	private AttrValueService valueService;
	
	// 修改属性
	@RequestMapping("/admin/value/valueUpdate")
	public String update(@RequestBody List<AttrValue> valueList){
		System.out.println("-----------------");
		for (int i = 0; i < valueList.size(); i++) {
			AttrValue aValue = (AttrValue)valueList.get(i);
			System.out.println("=====================value ===="+aValue.getName());
			valueService.update(aValue);
		}
		return "redirect:/admin/value/findByAttr2";
	}
	
	
	// 删除属性值
	@RequestMapping("/admin/value/delete")
	public String delete(int id){
		valueService.delete(id);
		return "redirect:/admin/value/findByAttr2"; 
	}
	
	// 新增属性值
	@RequestMapping("/admin/value/save")
	public String save(AttrValue avalue){
		Integer aid = avalue.getAttr_id();
		System.out.println("attr_id========="+aid);
		//avalue.setAttr_id(attr_id);
		valueService.save(avalue);
		return "redirect:/admin/value/findByAttr2";
	}
	
	@RequestMapping("/admin/value/valueSort")
	public String valueSort(@RequestParam("valueId")List<Integer> valueId,@RequestParam("valueSort")List<Integer> valueSort){
		System.out.println("进入 /admin/value/valueSort ----------");
		for (int i = 0; i < valueId.size(); i++) {
			// 下标遍历
			AttrValue aValue = valueService.updateSort(valueId.get(i),valueSort.get(i));
			System.out.println(aValue.toString());
		}
		return "redirect:/admin/value/findByAttr2";
	}
	
	@RequestMapping("/admin/value/findByAttr2")
	@ResponseBody
	public Map<String,Object> findByAttr(Integer aid) {
		Map<String, Object> map = new HashMap<>();	
		if(aid == null) {
			map.put("rows", Collections.emptyList());
		} else {
			map.put("rows", valueService.findByAttr2(aid));
		}
		return map;
	}
	
}
